import { login, getInfo } from "/@/api/user";
import { getStorage, setStorage, removeStorage } from "/@/utils/auth";
export interface UserStateType {
  name?: string;
  token?: string | null;
  roles?: any[];
}

export interface userInfo {
  username?: string;
  password?: string;
}
const state: UserStateType = {
  name: "",
  token: getStorage('Token'),
  roles: [],
};

const mutations = {
  SET_TOKEN: (state: UserStateType, token: string) => {
    state.token = token;
  },
  SET_NAME: (state: UserStateType, name: string) => {
    state.name = name;
  },
  SET_ROLES: (state: UserStateType, roles: any[]) => {
    state.roles = roles;
  },
};

const actions = {
  login(store: any, userInfo: userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve) => {
      login({ username: username, password: password })
        .then((res) => {
          // 保存token到store
          store.commit("SET_TOKEN", res.data);
          // 保存token到本地
          setStorage('Token',res.data);
          resolve("")
        })
    });
  },
  // get user info
  getInfo(store: any) {
    return new Promise((resolve, reject) => {
      getInfo(store.state.token)
        .then((res) => {
          console.log(res,"router  /*/*/*/");
          
          const { roles, name } = res.data;
          if (!roles || roles.length <= 0) {
            reject("用户角色信息不能为空");
          }
          // 保存用户信息到store
          store.commit("SET_ROLES", roles);
          store.commit("SET_NAME", name);
          resolve(res.data)
        })
        .catch(()=>{
          console.log("catch");
        })
    });
  },

  // user logout
  logout(store: any) {
    return new Promise((resolve, reject) => {
      // 退出登录，删除信息
      store.commit("SET_TOKEN", "");
      store.commit("SET_ROLES", []);
      removeStorage('Token');
      // resetRouter()
      resolve("");
    });
  },

  // remove token
  resetStorage(store: any) {
    return new Promise((resolve) => {
      store.commit("SET_TOKEN", "");
      store.commit("SET_ROLES", []);
      removeStorage('Token');
      resolve("");
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
